package com.xuyiwei.xblog.core.base.response;

import com.xuyiwei.xblog.core.exception.GunsException;
import com.xuyiwei.xblog.core.exception.GunsExceptionEnum;
import com.xuyiwei.xblog.core.exception.ServiceExceptionEnum;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;

/**
 * Created by xuyiwei on 2018/10/21.
 */
public class Result<T> extends BaseDomain implements Serializable {
    private String code;
    private String msg;
    private T data;

    private Result() {
        this.code = GunsExceptionEnum.SUCCESS.getCode();
        this.msg = GunsExceptionEnum.SUCCESS.getMessage();
    }

    private Result(T data) {
        this.code = GunsExceptionEnum.SUCCESS.getCode();
        this.msg = GunsExceptionEnum.SUCCESS.getMessage();
        this.setData(data);
    }

    private Result(String code, String msg) {
        this.code = GunsExceptionEnum.SUCCESS.getCode();
        this.msg = GunsExceptionEnum.SUCCESS.getMessage();
        this.setCode(code);
        this.setMsg(msg);
    }

    private Result(String code, String msg, T data) {
        this.code = GunsExceptionEnum.SUCCESS.getCode();
        this.msg = GunsExceptionEnum.SUCCESS.getMessage();
        this.setCode(code);
        this.setMsg(msg);
        this.setData(data);
    }

    public Result<T> setError(GunsException e) {
        this.setCode(e.getCode());
        this.setMsg(e.getMessage());
        return this;
    }

    public Result<T> setError(String code, String msg) {
        this.setCode(code);
        this.setMsg(msg);
        return this;
    }

    public Result<T> setError(ServiceExceptionEnum errorCode) {
        this.setCode(errorCode.getCode());
        this.setMsg(errorCode.getMessage());
        return this;
    }

    public boolean isSuccess() {
        return StringUtils.equals(this.getCode(), GunsExceptionEnum.SUCCESS.getCode());
    }

    public static <T> Result instance() {
        return new Result();
    }

    public static <T> Result instance(T data) {
        return new Result(data);
    }

    public static <T> Result instance(String code, String msg) {
        return new Result(code, msg);
    }

    public static <T> Result instance(String code, String msg, T data) {
        return new Result(code, msg, data);
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return this.msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
